package ddu.com.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import ddu.com.intercept.MyInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * @author 张霞
 * @version 1.0fastJsonHttpMessageConverter
 * @项目：mammon-web-platform
 * @描述：spring mvc中的（springmvc-controller） 环境配置,定制mvc
 * @创建时间 23:12 2018/4/14 0014
 * Only using @Bean methods within @Configuration classes is a recommended approach of
ensuring that 'full' mode is always used. This will prevent the same @Bean method from accidentally
being invoked multiple times and helps to reduce subtle bugs that can be hard to track down when
operating in 'lite' mode.
 */
@Slf4j
@Configuration
@ComponentScan(basePackages = {"ddu.com"}, includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Controller.class)}, useDefaultFilters = false)
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {


    public WebConfig() {
       log.info("WebConfig  加载---");
    }

    @Autowired
    private ServletContext servletContext;

    @Bean
    public ContextLoaderListener getContextLoaderListener(){
        ContextLoaderListener contextLoaderListener = new ContextLoaderListener();
        return  contextLoaderListener;
    }
/*    @Bean
    public ServletContext getServletContext(){
        servletContext.setInitParameter("logbackConfigLocation","classpath:logback.xml");
        servletContext.addListener(LogbackConfigListener.class);
        return servletContext;
    }*/
    /**
     * @auth: zhangxia
     * @desc: 可以用于添加默认返回页面
     * @methodName: addViewControllers
     * @params: [registry]
     * @return: void
     * @createTime: 2018/4/16 16:16
     * @version:2.1.6
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("welcome");
    }

    /**
     * @auth: zhangxia
     * @desc:添加拦截器
     * @methodName: addInterceptors
     * @params: [registry]
     * @return: void
     * @createTime: 2018/4/16 16:03
     * @version:2.1.6
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LocaleChangeInterceptor());
        registry.addInterceptor(new ThemeChangeInterceptor()).addPathPatterns("/**").excludePathPatterns("/welcome/**");
        registry.addInterceptor(new MyInterceptor());
    }

    /**
     * @auth: zhangxia
     * @desc: 配置静态资源路径,并配置对HTTP缓存的支持
     * @methodName: addResourceHandlers
     * @params: [registry]
     * @return: void
     * @createTime: 2018/4/16 16:24
     * @version:2.1.6
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/static/css/**").addResourceLocations("/css/").setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
        registry.addResourceHandler("/static/fonts/**").addResourceLocations("/fonts/").setCacheControl(CacheControl.maxAge(1,TimeUnit.HOURS).cachePublic());
        registry.addResourceHandler("/static/js/**").addResourceLocations("/js/").setCacheControl(CacheControl.maxAge(1,TimeUnit.HOURS).cachePublic());
    }


    /**
     * @param
     * @return org.springframework.web.controller.i18n.CookieLocaleResolver
     * @author:张霞
     * @description：当前请求的地区信息--配置地区信息，替换xml配置：（<bean id="localeResolver" class="org.springframework.web.controller.i18n.CookieLocaleResolver">
     * <property name="defaultLocale" value="zh_CN"/>
     * </bean>  ）
     * @method:getLocalResoler
     * @create time：2018/4/14 0014 23:18
     */
    @Bean(name = "localeResolver")
    public CookieLocaleResolver initLocalResolerConfig() {
        CookieLocaleResolver resolver = new CookieLocaleResolver();
        resolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        resolver.setCookieMaxAge(Integer.MAX_VALUE);//cookie被保存在客户端的最长时间。如果该值为-1，那么cookie将不会被持久化，在客户端浏览器关闭之后就失效了
        return resolver;
    }

    /**
     * @auth: zhangxia
     * @desc: 配置模板路径
     * @methodName: freeMarkerConfigurer
     * @params: []
     * @return: org.springframework.web.controller.view.freemarker.FreeMarkerConfigurer
     * @createTime: 2018/4/17 11:33
     * @version:2.1.6
     */
   /* @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPath("/WEB-INF/");
        return configurer;
    }*/

    /**
     * @param
     * @return com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter
     * @author:张霞
     * @description：支持返回json(避免IE在ajax请求时，返回json出现下载),替换xml配置：（<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
     * <property name="supportedMediaTypes">
     * <list>
     * <value>text/plain;charset=UTF-8</value>
     * <value>application/json;charset=UTF-8</value>
     * </list>
     * </property>
     * </bean>  ）
     * @method:converter
     * @create time：2018/4/14 0014 23:26
     */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new StringHttpMessageConverter());
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

        ArrayList<MediaType> list = new ArrayList<>();
        list.add(MediaType.valueOf("text/html;charset=UTF-8"));
        list.add(MediaType.valueOf("application/json;charset=UTF-8"));
        fastJsonHttpMessageConverter.setSupportedMediaTypes(list);
        converters.add(fastJsonHttpMessageConverter);
    }

    /** @author:张霞
     * @description：spring默认对模型视图添加前后缀,替换xml配置：（<bean id="viewResolver" class="org.springframework.web.controller.view.InternalResourceViewResolver"
    p:prefix="/views/" p:suffix=".jsp"/>  ）
     * @method:initViewResolver
     * @param
     * @return org.springframework.web.controller.view.InternalResourceViewResolver
     * @create time：2018/4/14 0014 23:32
     */
    /*@Bean(name = "viewResolver")
    public InternalResourceViewResolver initViewResolverCongig(){
        //视图解析器 InternalResourceViewResolver
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();//视图解析器
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".html");
        return viewResolver;
    }*/


    /**
     * @return org.thymeleaf.templateresolver.ServletContextTemplateResolver
     * @author:张霞
     * @description：应用中引用了thymeleaf前端框架需要如下初始化模型视图
     * @method:servletContextTemplateResolver
     * @create time：2018/4/15 0015 0:04
     */
    @Bean(name = "thymeleafResolver")
    public ServletContextTemplateResolver servletContextTemplateResolver() {
        ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(servletContext);
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode("HTML5");
        resolver.setCacheable(false);
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    /**
     * @param thymeleafResolver
     * @return org.thymeleaf.templateresolver.ServletContextTemplateResolver
     * @author:张霞
     * @description：应用中引用了thymeleaf前端框架需要如下初始化模型视图
     * @method:servletContextTemplateResolver
     * @create time：2018/4/15 0015 0:04
     */
    @Bean(name = "templateEngine")
    public SpringTemplateEngine springTemplateEngine(ServletContextTemplateResolver thymeleafResolver) {
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        springTemplateEngine.setTemplateResolver(thymeleafResolver);
        return springTemplateEngine;
    }

    /**
     * @param templateEngine
     * @return org.thymeleaf.templateresolver.ServletContextTemplateResolver
     * @author:张霞
     * @description：应用中引用了thymeleaf前端框架需要如下初始化模型视图
     * @method:servletContextTemplateResolver
     * @create time：2018/4/15 0015 0:04
     */
    @Bean
    public ThymeleafViewResolver thymeleafViewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine);
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }


    /** @author:张霞
     * @description：配置springMVC处理上传文件的信息 , 替换xml配置：（<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"/>
    <property name="maxUploadSize" value="10485760000"/>
    <property name="maxInMemorySize" value="40960"/>
    </bean>  ）
     * @method:initUploadConfig
     * @param
     * @return org.springframework.web.multipart.commons.CommonsMultipartResolver
     * @create time：2018/4/14 0014 23:36
     */
   /* @Bean(name = "multipartResolver")
    public CommonsMultipartResolver initUploadConfig(){
        //客户端上传文件
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        multipartResolver.setDefaultEncoding("utf-8");
        multipartResolver.setMaxUploadSize(Long.getLong("10485760000"));
        multipartResolver.setMaxInMemorySize(40960);
        return multipartResolver;
    }*/

}
